﻿using AsscerMVCN2512.Models;
using System;
using System.Linq;
using System.Web.Mvc;

namespace AssetManagementSystem.Controllers
{
    public class AssetInventoryController : Controller
    {
        private AssetDBEntities1 db = new AssetDBEntities1();

        public ActionResult Index()
        {
            return View();
        }

        [HttpGet]
        public JsonResult GetAssetInventoryList(int page = 1, int limit = 10, string assetName = "")
        {
            try
            {
                // 查询办公用品类型的资产ID
                var officeSupplyType = db.AssetTypeInfo
                    .FirstOrDefault(t => t.AssetTypeName.Contains("办公用品"));

                if (officeSupplyType == null)
                {
                    return Json(new { code = 1, msg = "未找到办公用品资产类型" }, JsonRequestBehavior.AllowGet);
                }

                int officeSupplyTypeId = officeSupplyType.AssetTypeID;

                // 先获取所有办公用品资产ID列表
                var officeAssetIds = db.AssetInfo
                    .Where(a => a.AssetTypeID == officeSupplyTypeId)
                    .Select(a => a.AssetID)
                    .ToList();

                // 查询入库数量
                var putInfo = db.AssetPutInfo
                    .Where(p => officeAssetIds.Contains(p.AssetID))
                    .GroupBy(p => p.AssetID)
                    .Select(g => new
                    {
                        AssetID = g.Key,
                        TotalPut = g.Sum(p => p.AssetPutCount)
                    })
                    .ToList();

                // 查询已领取数量（从办公用品领取记录）
                var receiveInfo = db.OfficeSuppliesRecordInfo
                    .Where(r => r.OfficeApplyState == 1 && officeAssetIds.Contains(r.AssetID))
                    .GroupBy(r => r.AssetID)
                    .Select(g => new
                    {
                        AssetID = g.Key,
                        TotalReceived = g.Sum(r => r.OfficeReceiveNum ?? 0)
                    })
                    .ToList();

                // 查询办公用品资产的基本信息
                var officeAssets = db.AssetInfo
                    .Where(a => a.AssetTypeID == officeSupplyTypeId)
                    .Select(a => new
                    {
                        a.AssetID,
                        a.AssetName,
                        a.AssetModel,
                        a.AssetCompany
                    })
                    .ToList();

                // 在内存中组合数据
                var query = from asset in officeAssets
                            let putItem = putInfo.FirstOrDefault(p => p.AssetID == asset.AssetID)
                            let receiveItem = receiveInfo.FirstOrDefault(r => r.AssetID == asset.AssetID)
                            select new
                            {
                                asset.AssetID,
                                asset.AssetName,
                                asset.AssetModel,
                                asset.AssetCompany,
                                TotalPut = putItem != null ? putItem.TotalPut : 0,
                                TotalUsed = receiveItem != null ? receiveItem.TotalReceived : 0,
                                TotalRemain = (putItem != null ? putItem.TotalPut : 0) - (receiveItem != null ? receiveItem.TotalReceived : 0)
                            };

                // 按资产名称筛选
                if (!string.IsNullOrEmpty(assetName))
                {
                    query = query.Where(x => x.AssetName.Contains(assetName));
                }

                // 分页
                var totalCount = query.Count();
                var list = query.OrderBy(x => x.AssetID)
                              .Skip((page - 1) * limit)
                              .Take(limit)
                              .ToList();

                return Json(new
                {
                    code = 0,
                    msg = "成功",
                    count = totalCount,
                    data = list
                }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"库存查询异常: {ex.Message}");
                System.Diagnostics.Debug.WriteLine($"堆栈跟踪: {ex.StackTrace}");
                return Json(new
                {
                    code = 1,
                    msg = "查询失败：" + ex.Message
                }, JsonRequestBehavior.AllowGet);
            }
        }
    }
}